package com.gjs.management.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gjs.common.exception.BizException;
import com.gjs.common.manager.response.RspBody;
import com.gjs.common.pojo.dto.request.PageQuery;
import com.gjs.common.pojo.dto.response.ListPageRsp;
import com.gjs.management.pojo.dto.agreement.AgreementDTO;
import com.gjs.management.pojo.dto.agreement.AgreementQueryDTO;
import com.gjs.management.pojo.entity.Agreement;
import com.gjs.management.service.IAgreementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@Api(tags = "协议及协议配置接口")
@RequiredArgsConstructor
@RequestMapping("/agreement")
public class AgreementController {

    private final IAgreementService agreementService;

    @GetMapping("/list")
    @ApiOperation("协议列表")
    public RspBody<ListPageRsp<AgreementDTO>> list(AgreementQueryDTO queryDTO,PageQuery pageQuery){
        IPage<Agreement> agreementIPage = agreementService.page(pageQuery.buildPage(),agreementService.buildWrapper(queryDTO));
        return RspBody.success(ListPageRsp.of(agreementIPage,AgreementDTO.class));
    }

    @GetMapping("/detail")
    @ApiOperation("协议详情")
    public RspBody<AgreementDTO> detail(Long id){
        Agreement agreement = agreementService.getById(id);
        if(agreement == null){
            throw new BizException("找不到该协议");
        }
        return RspBody.success(BeanUtil.copyProperties(agreement,AgreementDTO.class));
    }

    @PostMapping("/add")
    @ApiOperation("添加")
    public RspBody<AgreementDTO> add(@RequestBody AgreementDTO agreementDTO){
        Agreement agreement = BeanUtil.copyProperties(agreementDTO,Agreement.class);
        try{
            agreementService.save(agreement);
        }catch (Exception e){
            throw new BizException("添加协议失败");
        }

        return RspBody.success(BeanUtil.copyProperties(agreement,AgreementDTO.class));
    }

    @PostMapping("/update")
    @ApiOperation("更新")
    public RspBody<AgreementDTO> update(@RequestBody AgreementDTO agreementDTO){
        Agreement agreement = agreementService.getById(agreementDTO.getId());
        if(agreement == null){
            throw new BizException("找不到该协议");
        }

        try{
            BeanUtil.copyProperties(agreementDTO,agreement);
            agreementService.updateById(agreement);
        }catch (Exception e){
            throw new BizException("更新协议失败");
        }

        return RspBody.success(BeanUtil.copyProperties(agreement,AgreementDTO.class));
    }
}
